import { type Directive } from 'vue'
import { isArray } from 'lodash'
// import { useUserState } from '@/store/useUserState'

// 按钮及组件级别指令控制 需要传入权限值
// keysList 类似数据 "[\"addOrUpdateProject\",\"deleteProject\",\"noticeDelete\",\"setWhiteBtn\"]"
export const permission: Directive<HTMLElement, string> = {
  mounted(el, binding) {
    const { value } = binding
    const { userRoleInfo } = useUserState()
    const permission = userRoleInfo?.permission
    if (permission) {
      const keysList = JSON.parse(permission)
      // 如果是数组 校验多个权限是否都符合
      if (value !== 'home' && isArray(value)) {
        let j = 0
        for (let i = 0; i < value.length; i++) {
          const va = value[i]
          if (!keysList.includes(va)) {
            j++
          }
        }
        if (j === value?.length) {
          // 销毁Dom
          el.parentNode?.removeChild(el)
        }
        return
      }
      if (value !== 'home' && !keysList.includes(value)) {
        // 销毁Dom
        el.parentNode?.removeChild(el)
      }
    } else if (value !== 'home') {
      el.parentNode?.removeChild(el)
    }
  }
}
